import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.FrameWindow;
import com.gargoylesoftware.htmlunit.html.HtmlOption;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Scanner;

public class Spider {

    private static final String URL = "http://www.jwgl.hbnu.edu.cn";

    public static void main(String[] args) throws IOException {
        Connection connection = Jsoup.connect(URL);
        Connection.Response response = connection.method(Connection.Method.GET).execute();
        String cookie = response.cookie("safedog-flow-item");

        Document document = response.parse();

        String __VIEWSTATE =
                document.getElementsByAttributeValue("name", "__VIEWSTATE").first().val();
        String __VIEWSTATEGENERATOR =
                document.getElementsByAttributeValue("name", "__VIEWSTATEGENERATOR").first().val();

        java.net.URL url = new URL(
                response.url().toString()
                        .substring(0, response.url().toString().lastIndexOf("/") + 1) + "CheckCode.aspx");
        FileOutputStream fout = new FileOutputStream(new File("/home/version/a.gif"));
        InputStream in = url.openConnection().getInputStream();
        int i;
        while ((i = in.read()) != -1) {
            fout.write(i);
        }
        fout.close();
        in.close();

        Scanner scanner = new Scanner(System.in);
        String code = scanner.nextLine();
        scanner.close();

        Connection conn = Jsoup.connect(response.url().toString());
        conn.data("__VIEWSTATE", __VIEWSTATE);
        conn.data("__VIEWSTATEGENERATOR", __VIEWSTATEGENERATOR);
        conn.data("txtUserName", "2015116020243");
        conn.data("Textbox1", "");
        conn.data("Textbox2", "qaz53589793");
        conn.data("txtSecretCode", code);
        conn.data("RadioButtonList1", URLEncoder.encode("学生", "gb2312"));
        conn.data("Button1", "");
        conn.data("lbLanguage", "");
        conn.data("hidPdrs", "");
        conn.data("hidsc", "");

        conn.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        conn.header("Content-Type", "application/x-www-form-urlencoded");
        conn.header("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36");
        conn.header("Cookie", "safedog-flow-item=" + cookie);
        conn.header("Origin", "http://www.jwgl.hbnu.edu.cn");
        conn.header("Referer", response.url().toString());
        Connection.Response post = conn.method(Connection.Method.POST).execute();

        htmlUnit(post.url());
    }

    private static void htmlUnit(URL url) throws IOException {
        WebClient webClient = new WebClient(BrowserVersion.CHROME);
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());
        webClient.setAlertHandler((page, message) -> {
            System.out.println(message);
        });
        HtmlPage page = webClient.getPage(url);
        page.getAnchorByText("信号与系统").click();

        FrameWindow element = page.getFrames().get(0);
        HtmlPage framePage = (HtmlPage) element.getEnclosedPage();

        HtmlSelect select = framePage.getHtmlElementById("pjkc");

        List<HtmlOption> options = select.getOptions();
        final int end = select.getOptionSize();
        int count = 0;
        for (HtmlOption p : options) {
            count ++;
            p.click();
            HtmlPage framePage1 = (HtmlPage) element.getEnclosedPage();
            List<HtmlSelect> list = framePage1.getByXPath("//select");
            list.remove(0);
            boolean flag = true;
            for (HtmlSelect htmlSelect : list) {
                if (flag) {
                    htmlSelect.getOption(2).click();
                    flag = false;
                } else {
                    htmlSelect.getOption(1).click();
                }
            }
            framePage1.getHtmlElementById("Button1").click();
            if(count == end) {
                HtmlPage framePage2 = (HtmlPage) element.getEnclosedPage();
                framePage2.getHtmlElementById("Button2").click();
            }
        }
    }
}
